package com.hy.study.practice.sparse;

/**
 * 第二次练习 稀疏数组
 */
public class SparseArrayDemo2 {
    private static final int Max_ROWS = 11;
    private static final int Max_COLS = 11;

    public static void main(String[] args) {
        int[][] arr = new int[Max_ROWS][Max_COLS];
        arr[0][0] = 1;
        arr[1][1] = 1;
        arr[2][2] = 1;
        arr[3][3] = 1;
        arr[4][4] = 1;
        arr[5][5] = 1;
        arr[6][6] = 1;
        arr[7][7] = 1;
        arr[8][8] = 1;
        arr[9][9] = 1;
        arr[10][10] = 1;


        System.out.println("---------------原始数组---------");
        show(arr);
        int[][] sparseArray = arryToSparseArray(arr);
        System.out.println("--------------稀疏数组--------------");
        show(sparseArray);
        int[][] array = sparseArrayToArray(sparseArray);
        System.out.println("---------------使用稀疏数组换原的数组--------------");
        show(array);

    }

    /**
     * 普通数组转换成稀疏数组
     *
     * @param arr
     * @return
     */
    public static int[][] arryToSparseArray(int arr[][]) {
        int row = arr.length;
        int clo = arr[0].length;
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                int temp = arr[i][j];
                if (temp != 0) {
                    count++;
                }
            }
        }

        int[][] sparseArray = new int[count + 1][3];
        sparseArray[0][0] = row;
        sparseArray[0][1] = clo;
        sparseArray[0][2] = count;
        int index = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                int temp = arr[i][j];
                if (temp != 0) {
                    index++;
                    sparseArray[index][0] = i;
                    sparseArray[index][1] = j;
                    sparseArray[index][2] = temp;
                }
            }
        }
        return sparseArray;


    }

    /**
     * 稀疏数组转换为普通数组
     *
     * @param sparseArray
     * @return
     */
    public static int[][] sparseArrayToArray(int sparseArray[][]) {
        int[][] arr = new int[sparseArray[0][0]][sparseArray[0][1]];
        //从 1 开始  第一行 是存原始 数组的信息
        for (int i = 1; i < sparseArray.length; i++) {
            arr[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }
        return arr;

    }

    public static void show(int arr[][]) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.printf("%d\t", arr[i][j]);
            }
            System.out.println("");
        }
    }
}
